#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/4/15 15:10
# @Author  : Chenmm
# @File    : SysUer.py
# @Software: PyCharm

from app import db, loginmanager
from flask_login import UserMixin, AnonymousUserMixin
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from app.models import SysDept
from app import db


@loginmanager.user_loader
def load_user(user_id):
    return SysUser.query.get(int(user_id))




class SysUserRole(db.Model):
    __tablename__ = 'sys_user_role'

    user_id = db.Column(
        db.BigInteger,
        db.ForeignKey('sys_user.id'),  # 添加外键指向 sys_user.id
        primary_key=True,
        comment='用户ID'
    )
    role_id = db.Column(
        db.BigInteger,
        db.ForeignKey('sys_role.id'),  # 添加外键指向 sys_role.id
        primary_key=True,
        comment='角色ID'
    )

    __table_args__ = (
        db.UniqueConstraint('user_id', 'role_id', name='uk_userid_roleid'),
        {'comment': '用户和角色关联表'}
    )




class SysUser(db.Model, UserMixin):
    __tablename__ = 'sys_user'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    username = db.Column(db.String(64), unique=True, comment='用户名')
    nickname = db.Column(db.String(64), comment='昵称')
    gender = db.Column(db.SmallInteger, default=0, comment='性别((1-男 2-女 0-保密)')
    password_hash = db.Column(db.String(255), comment='密码')
    dept_id = db.Column(db.Integer, comment='部门ID')
    avatar = db.Column(db.String(255), comment='用户头像')
    mobile = db.Column(db.String(20), comment='联系方式')
    status = db.Column(db.SmallInteger, default=0, comment='状态(1-正常 0-禁用)')
    email = db.Column(db.String(128), comment='用户邮箱')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    create_by = db.Column(db.BigInteger, comment='创建人ID')
    update_time = db.Column(db.DateTime, onupdate=datetime.now, comment='更新时间')
    update_by = db.Column(db.BigInteger, comment='修改人ID')
    is_deleted = db.Column(db.SmallInteger, default=0, comment='逻辑删除标识(0-未删除 1-已删除)')
    openid = db.Column(db.String(28), comment='微信 openid')


    roles = db.relationship(
        'SysRole',
        secondary='sys_user_role',  # 指定中间表
        backref=db.backref('users', lazy='dynamic')  # 定义反向引用
    )

    __table_args__ = (
        db.UniqueConstraint('username', name='login_name'),
        {'comment': '用户信息表'}
    )


    def __repr__(self):
        return '<SysUser %r>\n' % (self.username)

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)


    def to_pageination_dict(self):
        user = {
            'id': self.id,
            'username': self.username,
            'nickname': self.nickname,
            'mobile': self.mobile,
            'gender': self.gender,
            'avatar': self.avatar,
            'email': self.email,
            'status': self.status,
            # 'deptName': SysDept.query.filter_by(id=self.dept_id).first().name,
            'roleNames': ','.join([role.name for role in self.roles]),
            'createTime': self.create_time,
            'dept_id': self.dept_id
        }
        return user

    def to_option_json(self):
        option = {
            'value': self.id,
            'label': self.nickname,
        }

        return option





